package com.hyt.it.ogt.kq.service.bm.den;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hyt.core.util.FastJsonUtil;
import com.hyt.it.ogt.kq.service.bm.model.dto.ExcelDto;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

@Slf4j
public class EasyexcelUtil {

    /**
     * 根据url下载文件流
     * @param urlStr
     * @return
     */
    public static InputStream getInputStreamFromUrl(String urlStr) {
        InputStream inputStream=null;
        try {
            //url解码
            URL url = new URL(urlStr);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
            // 将返回的输入流转换成字符串
            inputStream = httpUrlConn.getInputStream();
        } catch (IOException e) {
        	log.error("## getInputStreamFromUrl error", e);
        }
        return inputStream;
    }
    
    /**
     * 获取excel中的数据
     *
     * @param inputStream
     * @param templateConfigs
     * @return
     */
    public static ExcelDto getExcelDataList(InputStream inputStream) {
    	ExcelDto excelDto = new ExcelDto();
        List<Map<String, String>> cachedDataList = Lists.newCopyOnWriteArrayList();
        EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer, String>>() {
            //index -> code
            final Map<Integer, String> headMap = Maps.newConcurrentMap();

            @Override
            public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
                log.info("# 导入数据Excel表头：{}", JSON.toJSONString(headMap));
                headMap.forEach((key, value) -> {
                    this.headMap.put(key, value);
                });
                excelDto.setHeadMap(headMap);
            }

            @Override
            public void invoke(Map<Integer, String> data, AnalysisContext context) {
                log.info("# 导入数据Excel解析行数据:{}", JSON.toJSONString(data));
                Map<String, String> certificateExamineesData = Maps.newHashMap();
                headMap.forEach((key, value) -> {
                    certificateExamineesData.put(value, data.get(key));
                });
                cachedDataList.add(certificateExamineesData);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                log.info("# 导入数据所有数据解析完成！");
                if (log.isDebugEnabled()) {
                    log.debug("# 导入数据所有解析数据：{}", FastJsonUtil.getBeanToJson(cachedDataList));
                }
            }
        }).sheet().doRead();
        excelDto.setRowDataList(cachedDataList);
        return excelDto;
    }
}
